package com.ht.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ht.util.JsonResult;
import com.ht.util.JwtUtils;
import com.ht.util.ResultEnum;
import com.ht.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName TokenFilter
 * @Description TODO（核心token验证过滤器）
 * @Author hejialun
 * @Date 2022/3/17 15:29
 * @Version 1.0
 */
@Component
public class TokenFilter extends OncePerRequestFilter {
    //定义不需要登录的api
    private static final List<String> notLoginApi = new ArrayList<String>() {{
        add("/sys-login/wxLogin");
    }};

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //判断当前访问接口是否需要登录
        if (notLoginApi.indexOf(request.getRequestURI()) != -1) {
            filterChain.doFilter(request, response);
            return;
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String token = UserUtil.getTokenByRequest();
        if (ObjectUtil.isEmpty(token)) {
            response.getWriter().print(JSON.toJSONString(JsonResult.error(ResultEnum.USER_NEED_AUTHORITIES.getMessage(), ResultEnum.USER_NEED_AUTHORITIES.getCode())));
            return;
        }
        //解析token是否存在id
        String id = JwtUtils.getKey(token, "id");
        if (StrUtil.isEmpty(id)) {
            response.getWriter().print(JSON.toJSONString(JsonResult.error(ResultEnum.TOKEN_ABNORMAL.getMessage(), ResultEnum.TOKEN_ABNORMAL.getCode())));
            return;
        }
        filterChain.doFilter(request, response);
    }


}
